Member-only story

Hardcore Gas Savings in NFT Minting (Part 3): Save $30,000 in Presale Gas Using Bit Manipulation

Photo by Glenn Carstens-Peters on Unsplash

This series has a Part 1 and Part 2. If you see a paywall, click here.

In a public mint, people can generally mint as many NFTs as they want to, either by minting over and over or by colluding with other buyers. This is undesirable in a private sale (sometimes known as a whitelist) where each member on the list is guaranteed a specified number of mints. A typical workflow would look something like this in solidity:

(Please note that this does not include the optimizations listed in Part 1 for the sake of brevity. Don’t actually use this code! It doesn’t have require messages!)

This workflow should look familiar to anyone who has programmed an NFT before. After we implement all the optimizations in Part 1 and Part 2, there is still one more thing to do.

The culprit for unnecessarily high gas costs here is amountMintedSoFar[msg.sender]++ . That variable is a mapping from the addresses to how many that user has minted so far and we want to make sure it doesn’t exceed their allocation.

Although this should be an obvious solution for any seasoned programmer (hash maps have a notorious reputation that they are always the correct answer at an interview), mapping addresses to integers has a drawback when used on Ethereum.

By way of review, if we have a mapping mapping (address => uin256) myMap , the operation myMap[myAddress] += 1 costs 20,000 gas when it is executed the first time, because setting a zero value to non-zero in Ethereum costs that much. Non-zero to non-zero is much cheaper at 5,000 gas. So myMap[myAddress] += 1 costs 5,000 gas if the uint value inside is not zero.

Also, as a review, the translation to gas cost to dollars is as follows:

cost in $ = gas used × gas price (gwei) × ETH price ($) / 1 Billion

You can get the current gas price from sites like etherscan or ethgasstation.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (2)

Write a response